package secondriver.springsubway.example.jta;

import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.Transaction;

import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.jta.TransactionFactory;

public class TestAtomikos2 {

	public static ApplicationContext ctx;

	@BeforeClass
	public static void beforeClass() {
		ctx = new ClassPathXmlApplicationContext(
				"classpath:integration/spring-jta.xml");
	}

	public static void afterClass() {
		ctx = null;
	}

	@Test
	public void test1() {
		exe("abc", "abc");
	}

	@Test
	public void test2() {
		exe("123=", "123");
	}

	public void exe(String av, String bv) {
		TransactionFactory txm = (TransactionFactory) ctx
				.getBean("transactionManager");

		JdbcTemplate a = (JdbcTemplate) ctx.getBean("jdbcTemplateA");
		JdbcTemplate b = (JdbcTemplate) ctx.getBean("jdbcTemplateB");
		Transaction tx = null;
		try {
			tx = txm.createTransaction("tx-name-define", 10000);
			a.update("insert into jta_temp (value) values('" + av + "')");
			b.update("insert into jta_temp (value) values('" + bv + "')");
			tx.commit();
		} catch (NotSupportedException | SystemException | SecurityException
				| RollbackException | HeuristicMixedException
				| HeuristicRollbackException e) {
			e.printStackTrace();
			if (null != tx) {
				try {
					tx.rollback();
				} catch (IllegalStateException | SystemException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
}
